package com.bamboo.tool.config;

import com.bamboo.tool.config.model.RestfulCloudConfig;
import com.bamboo.tool.enums.RequestMethod;
import com.bamboo.tool.enums.SoaType;
import com.bamboo.tool.store.Impl.SqliteStoreServiceImpl;
import com.bamboo.tool.store.StoreService;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;

/**
 * Create by GuoQing
 * Date 2022/1/20 10:58
 * Description
 *
 * @author bamboo
 */
@State(name = "restfulCloudConfig", storages = {@Storage("restfulCloudConfig.xml")})
public class BambooToolComponent implements PersistentStateComponent<RestfulCloudConfig> {

    private RestfulCloudConfig toolConfig;

    @Override
    public @Nullable RestfulCloudConfig getState() {
        if (Objects.isNull(toolConfig)) {
            toolConfig = new RestfulCloudConfig();
            toolConfig.setSelectProjects(new HashSet<>());
            toolConfig.setSelectSoaTypes((new HashSet<>(List.of(SoaType.values()))));
            toolConfig.setSelectRequestTypes(new HashSet<>(List.of(RequestMethod.values())));
        }
        return toolConfig;
    }

    @Override
    public void loadState(@NotNull RestfulCloudConfig state) {

        XmlSerializerUtil.copyBean(state, Objects.requireNonNull(getState()));
    }

    public static BambooToolComponent getInstance(Project project) {
        return project.getService(BambooToolComponent.class);
    }

    public static StoreService getStoreService() {
        StoreService storeService = new SqliteStoreServiceImpl();
        return storeService;
    }

}
